import { ref, reactive, onMounted, nextTick } from 'vue'
import { saveExpressNumApi, getExpressListApi } from '@/api/logistics'
import useInstance from '@/hooks/useInstance'
import { LogisticParm } from '@/api/logistics/LogisticModel'
import { Toast } from '@nutui/nutui'
import { useRoute, useRouter } from 'vue-router'

export default function useSetting() {
	const route = useRoute()
	const router = useRouter()
	const ruleForm = ref()
	const { global } = useInstance()
	const formData = reactive<LogisticParm>({
		id: undefined,
		order_id: undefined,
		express_num: undefined,
		express_company: undefined
	})
	const rules = {
		express_num: [{ required: true, message: '请输入快递单号' }],
		express_company: [{ required: true, message: '请输入快递公司' }]
	}
	//新增
	const editBtn = async () => {
		let res = await saveExpressNumApi({ ...formData })
		if (res && res.code == 0) {
			Toast.success('编辑成功')

			// 返回上一页面
			router.go(-1)
		} else {
			Toast.fail('编辑失败')
		}
	}

	const submit = () => {
		formData.order_id = route.params.order_id as any
		// editBtn();
		ruleForm.value.validate().then(({ valid, errors }: any) => {
			if (valid) {
				editBtn()
			} else {
				console.log('error submit!!', errors)
			}
		})
	}
	const getData = async () => {
		let res = await getExpressListApi({
			order_id: route.params.order_id as any
		})
		if (res && res.code == 0) {
			nextTick(() => {
				//把要编辑的数据复制到表单绑定的对象
				global.$objCoppy(res.result, formData)
			})
		}
	}

	onMounted(() => {
		getData()
	})
	return {
		editBtn,
		formData,
		submit,
		ruleForm,
		rules
	}
}
